package com.hr.controller.user;


import com.hr.service.AiFunctionService;
import com.hr.service.impl.ChatMemoryImpl;
import com.hr.utils.Result;
import com.hr.utils.UserContext;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor;

import org.springframework.ai.chat.messages.Message;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.List;

@RestController
@RequestMapping("/ai")
@Slf4j
@Tag(name = "AI服务")
@AllArgsConstructor
public class AiFunctionController {

    private final ChatClient chatClient;

    private final ChatMemoryImpl chatMemory;

    private final AiFunctionService aiFunctionService;
    /**
     * AI聊天
     * @param message
     * @param chatId
     * @return
     */
    @GetMapping(value = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @Operation(summary = "AI聊天")
    public Flux<String> chat(@RequestParam String message, @RequestParam String chatId) {


        // 在主线程中获取 userId（此时 UserContext 有效）
        Long userId = UserContext.getUserId();
        log.info("登录人id: {}", userId);
        if (userId == null) {
            return Flux.error(new RuntimeException("未登录"));
        }
        //把chatId和userId合并，直接传递进去，进去再拆，这样就能避免线程问题
        String combinedConversationId = userId + ":" + chatId;

        // 指定会话ID，由MessageChatMemoryAdvisor自动管理记忆
        return chatClient.prompt()
                .user(message)
                // 指定会话ID，由MessageChatMemoryAdvisor自动管理记忆
                .advisors(advisorSpec -> advisorSpec
                        .param(AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY, combinedConversationId))
                .stream()
                .content()
                .doOnNext(c -> log.info("发送: {}", c));

    }
    /**
     * 获取消息列表
     * @param chatId
     * @return
     */
    @GetMapping("/MessageList/history/{chatId}")
    @Operation(summary = "获取消息列表")
    public Result getMessageList(@PathVariable("chatId") String chatId) {
        Long userId = UserContext.getUserId();
        if (userId == null) throw new RuntimeException("未登录");

        String combinedId = userId + ":" + chatId;
        List<Message> messages = chatMemory.get(combinedId, 10);
        return Result.success(messages);
    }

    /**
     * 获取对话历史
     * @return
     */
    @GetMapping("/conversation/history")
    @Operation(summary = "获取对话历史")
    public Result getHistory() {
        Long userId = UserContext.getUserId();
        //测试情况，测试用户ID为1
        /*if (userId == null){
            userId = 1L;
        }*/
        if (userId == null){
            return Result.error("请先登录");
        }
        List<String> conversations = aiFunctionService.getConversationList(String.valueOf(userId));

        return Result.success(conversations);
    }







}
